<template>
  <div class="chart" ref="chartWrapRef">
    <chart
      ref="chartRef"
      :option="refChartOption"
      :style="{ height: chartHeight }"
      @zrender:click="renderClickHandle"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, PropType, watch, onMounted } from 'vue';
import { Chart } from '@/components';
import { getDataZoomVisibie, getDatazoomEnd } from '../util';
export interface BarItem {
  [key: string]: string | number;
}

export default defineComponent({
  emits: ['zrender:click'],
  props: {
    data: {
      type: Array as PropType<BarItem[]>,
      default: () => [],
    },
    height: {
      type: Number,
      default: 300,
    },
    type: {
      type: String,
      default: '0',
    },
    fieldNames: {
      type: Object,
      default: () => ({
        name: 'name',
        value: 'value',
      }),
    },
    legend: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  setup(props, { emit }) {
    const chartRef = ref<any>();
    const legend = computed(() => props.legend);
    const chartWrapRef = ref();
    // const areaStyle = ref<any>({});
    const chartOption = {
      //   color: ['#E99220', 'rgba(233, 146, 32, 0.4)'],
      tooltip: {
        trigger: 'axis',
      },
      grid: {
        left: 50,
        right: 50,
        bottom: 40,
        top: 40,
      },
      dataZoom: [
        {
          id: 'dataZoomX',
          show: true,
          showDataShadow: 'auto',
          xAxisIndex: [0],
          filterMode: 'filter',
          start: 0,
          end: 20,
          minValueSpan: 1,
          maxValueSpan: 20,
          orient: 'horizontal',
          zoomLock: false,
          height: 15,
          bottom: 0,
          borderColor: 'transparent', //  边框颜色
        },
      ],
      legend: {
        data: legend,
      },
      xAxis: {
        type: 'category',
        data: [] as string[],
        axisPointer: {
          type: 'shadow',
        },
      },
      yAxis: {
        type: 'value',
        minInterval: 1,
        axisLabel: {
          formatter: '{value}',
        },
        axisTick: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
          },
        },
      },
      series: [
        {
          name: legend.value[0],
          type: 'bar',
          barWidth: 20,
          barGap: '0',
          itemStyle: {
            normal: {
              color: '',
              label: {
                show: true,
                position: 'top',
                rotate: 30,
                textStyle: {
                  fontWeight: 'bolder',
                  fontSize: '12',
                },
              },
            },
          },
          data: [] as number[],
        },
        {
          name: legend.value[1],
          type: 'bar',
          barWidth: 20,
          itemStyle: {
            color: '',
            normal: {
              color: '',
              label: {
                show: true,
                position: 'top',
                rotate: 30,
                textStyle: {
                  fontWeight: 'bolder',
                  fontSize: '12',
                },
              },
            },
          },
          data: [] as number[],
        },
      ],
    };

    const refChartOption = ref(chartOption);

    const chartHeight = computed(() => `${props.height}px`);

    const setChartOption = (data: any[]) => {
      const xAxis: string[] = [];
      interface SeriesDataMap {
        [key: string]: Array<any>;
      }
      const seriesDataMap: SeriesDataMap = {};
      data.forEach(item => {
        const name = item[props.fieldNames.name];
        props.fieldNames.values.forEach(value => {
          if (seriesDataMap[value]) {
            seriesDataMap[value].push(item[value]);
          } else {
            seriesDataMap[value] = [item[value]];
          }
        });
        xAxis.push(name);
      });
      refChartOption.value.xAxis.data = xAxis;
      refChartOption.value.dataZoom[0].show = getDataZoomVisibie(chartWrapRef.value, data.length);
      refChartOption.value.dataZoom[0].end = getDatazoomEnd(chartWrapRef.value, data.length);
      Object.values(seriesDataMap).forEach((o, i) => {
        refChartOption.value.series[i].data = o;
      });
    };

    const renderClickHandle = e => {
      if (e?.topTarget?.type === 'Rect') {
        const index = chartRef.value.getIndexByEvent(e);
        const item = props.data[index];
        emit('zrender:click', index, item);
      }
    };

    watch(
      () => props.data,
      () => {
        setChartOption(props.data);
      },
    );
    watch(
      () => props.type,
      () => {
        if (props.type == '1') {
          chartOption.series[0].itemStyle.normal.color = '#E99220';
          chartOption.series[1].itemStyle.normal.color = 'rgba(233,146,32,0.5)';
        } else if (props.type == '2') {
          chartOption.series[0].itemStyle.normal.color = '#1CCAFF';
          chartOption.series[1].itemStyle.normal.color = 'rgba(28,202,255,0.5)';
        } else {
          chartOption.series[0].itemStyle.normal.color = '#3191FF';
          chartOption.series[1].itemStyle.normal.color = 'rgba(49,145,255,0.5)';
        }
        setChartOption(props.data);
      },
      {
        immediate: true,
        deep: true,
      },
    );
    onMounted(() => {
      setChartOption(props.data);
    });

    return {
      chartHeight,
      refChartOption,
      renderClickHandle,
      chartRef,
      chartWrapRef,
    };
  },
  components: {
    Chart,
  },
});
</script>

<style scoped></style>
